package sample;

import java.io.IOException;
import java.util.Properties;

import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class EmailServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response)
                   throws ServletException, IOException {
    	System.out.println("doGet");
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, 
                          HttpServletResponse response)
                   throws ServletException, IOException {
    	System.out.println("doPost");
        processRequest(request, response);
    }

	protected void processRequest(HttpServletRequest request, 
								  HttpServletResponse response)
			throws ServletException, IOException {
		
        final String forward_error 		= "/error.jsp";		//	送信成功後に表示
        final String forward_success 	= "/success.jsp";	//	例外発生時に表示

        //	リクエストパラメータを取得する
        request.setCharacterEncoding("UTF-8");
        
        String from 	= request.getParameter("from");
        String to 		= request.getParameter("to");
        String subject 	= request.getParameter("subject");
        String message 	= request.getParameter("message");
        String login 	= request.getParameter("login");
        String password = request.getParameter("password");
        
        System.out.println(subject);
        System.out.println(message);

        try {
        	//	SMTPサーバ接続情報を生成
            Properties props = new Properties();
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");

            //	アカウント情報を生成
            Authenticator auth = new SMTPAuthenticator(login, password);

            //	Mailセッションを取得
            Session session = Session.getInstance(props, auth);

            MimeMessage msg = new MimeMessage(session);

            String[] langs = {"ja"};
            msg.setContentLanguage(langs);
            msg.setText(message, "UTF-8");
            msg.setSubject(subject, "UTF-8");
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            
            //	メール送信
            Transport.send(msg);

            RequestDispatcher dispatcher = request.getRequestDispatcher(forward_success);
            dispatcher.forward(request, response);
        }
        catch (AuthenticationFailedException ex) {	//	認証に失敗
            request.setAttribute("ErrorMessage", "Authentication failed");
            ex.printStackTrace();

            RequestDispatcher dispatcher = request.getRequestDispatcher(forward_error);
            dispatcher.forward(request, response);

        }
        catch (AddressException ex) {				//	メールアドレスが不正
            request.setAttribute("ErrorMessage", "Wrong email address");
            ex.printStackTrace();

            RequestDispatcher dispatcher = request.getRequestDispatcher(forward_error);
            dispatcher.forward(request, response);

        }
        catch (MessagingException ex) {				//	送信に関する例外
            request.setAttribute("ErrorMessage", ex.getMessage());
            ex.printStackTrace();

            RequestDispatcher dispatcher = request.getRequestDispatcher(forward_error);
            dispatcher.forward(request, response);
        }
	}
	
	private class SMTPAuthenticator extends Authenticator {
        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password) {
            authentication = new PasswordAuthentication(login, password);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }
}
